﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Transactions;
using Bids.Core.DomainObjects;
using Bids.Data;
using Bids.Web.Model;
using Bids.Core.Common.Data;
using Bids.Service;
using Bids.Core.Common.Security;


namespace Bids.Web.Controllers
{
    public class PublishController : Controller
    {
        #region
        IRepository<Contribution> _iRpoContribution;
        IRepository<Task> _iRpoTask;
        IRepository<Style> _iRpoStyle;
        IRepository<UsedFor> _iUsedFor;
        IRepository<SetMeal> _iRpoSetMeal;
        IRepository<Trade> _iRpoTrade;
        IUserContext _iUserContext;
        IAuthenticationService _iAuthSrv;
       
        IRepository<User> _iRpoUser;
        public PublishController(IRepository<Contribution> iRpoContribution
            , IRepository<Task> iRpoTask
            , IRepository<Style> iRpoStyle
            , IRepository<UsedFor> iUsedFor
            , IRepository<SetMeal> iRpoSetMeal
            , IRepository<Trade> iRpoTrade
            , IUserContext iUserContext
            , IAuthenticationService iAuthSrv
            
            , IRepository<User> iRpoUser)
        {
            _iRpoContribution = iRpoContribution;
            _iRpoTask = iRpoTask;
            _iRpoStyle = iRpoStyle;
            _iUsedFor = iUsedFor;
            _iRpoSetMeal = iRpoSetMeal;
            _iRpoTrade = iRpoTrade;
            _iUserContext = iUserContext;
            _iAuthSrv = iAuthSrv;
            
            _iRpoUser = iRpoUser;
        }
        #endregion


        public ActionResult Index()
        {
            var task = new Task();
            Session["NewTask"] = task;
            return View("step_1");
        }
        [HttpPost]
        public ActionResult Step_2()
        {
            if (Session["NewTask"] == null)
                return RedirectToAction("", "publish");
            var task = (Task)Session["NewTask"];
            UpdateModel(task);
            PublishModel model = new PublishModel();
            model.Trades = _iRpoTrade.FindAll().ToList();
            return View(model);
        }
        [HttpPost]
        public ActionResult Step_3(FormCollection form)
        {
            if (Session["NewTask"] == null)
                return RedirectToAction("", "publish");
            var task = (Task)Session["NewTask"];
            UpdateModel(task);
            task.Trade = _iRpoTrade.Find(task.TradeId);
            task.Feature = string.Format("{0},{1},{2}", form["Feature1"], form["Feature2"], form["Feature3"]);

            PublishModel model = new PublishModel();
            model.Styles = _iRpoStyle.FindAll().ToList();
            model.UsedFor = _iUsedFor.FindAll().ToList();
            return View(model);
        }
        [HttpPost]
        public ActionResult Step_4(FormCollection form)
        {
            if (Session["NewTask"] == null)
                return RedirectToAction("", "publish");

            var task = (Task)Session["NewTask"];
            UpdateModel(task);
            task.BadColor = form["BadColor"];
            task.GoodColor = form["GoodColor"];
            task.Expression = form["Expression"];

            Session["ExtraneousFile"] = Request.Files["ExtraneousFile"];

            foreach (var item in form["StyleId"].Split(','))
            {
                int styleId = item.ToInt32();
                var style = _iRpoStyle.Find(styleId);
                task.Styles.Add(style);
            }
            foreach (var item in form["UsedForId"].Split(','))
            {
                int usedForId = item.ToInt32();
                var usedFor = _iUsedFor.Find(usedForId);
                task.UsedFor.Add(usedFor);
            }
            PublishModel model = new PublishModel();
            model.SetMeals = _iRpoSetMeal.FindAll().ToList();
            return View(model);
        }
        [HttpPost]
        public ActionResult Step_5()
        {
            if (Session["NewTask"] == null)
                return RedirectToAction("", "publish");
            var task = (Task)Session["NewTask"];
            UpdateModel(task);
            task.SetMeal = _iRpoSetMeal.Find(task.SetMealId);
            return View(task);
        }
        [HttpPost]
        public ActionResult Step_6(User user)
        {
            try
            {
                using(TransactionScope ts = new TransactionScope())
                {
                    if (!_iUserContext.IsLogined || _iUserContext.User.UserType == UserType.设计师)
                    {
                        //如果已登录用户是设计师，则注销
                        _iAuthSrv.SignOut();
                        user.UserName = user.Phone;
                        user.Login = new Login
                        {
                            UserName = user.Phone,
                            Password = Request.Form["Password"].ToMD5()
                        };
                        //注册新用户
                        _iRpoUser.Add(user);
                            //登录
                            _iAuthSrv.SignIn(user, false);
                        
                    }
                    else
                    {
                        user = _iUserContext.User;
                    }

                    var task = (Task)Session["NewTask"];
                    task.Employer = user;
                    task.SetMeal = null;
                    task.Trade = null;
                    task.CreateTime = DateTime.Now;
                    task.Status = (int)TaskStatus.未付款;
                    var styleid = task.Styles.Select(t => t.ID).ToList();
                    var usedforid = task.UsedFor.Select(t => t.ID).ToList();
                    var styles = _iRpoStyle.Where(t => styleid.Contains(t.ID)).ToList();
                    var usedfors = _iUsedFor.Where(t => usedforid.Contains(t.ID)).ToList();
                    task.Styles.Clear();
                    task.UsedFor.Clear();
                    _iRpoTask.Add(task);

                    foreach (var item in styles)
                    {
                        item.Tasks.Add(task);
                    }
                    foreach (var item in usedfors)
                    {
                        item.Tasks.Add(task);
                    }

                    ts.Complete();
                    return View(task);
                }
            }
            catch (Exception e)
            {

                return View("Step_5");
            } 
        
        }
        public ActionResult Step_6( )
        {
            return View();
        }
    }
}
